<template>
	<view class="page-wrap" :data-theme="theme" :class="theme" :style="globalColor.style">
		<HeadCustom></HeadCustom>
		<SearchCustom :keyword.sync="keyword" @search="getSearch" @change="getSearch" />
		<view class="mt8"></view>
		<view id="container" class="tui-maps"></view>
		<view class="gps-body" v-if="surroundingPois.length > 0">
			<scroll-view class="scroll" scroll-y="true" :scroll-top="scrollTop" scroll-with-animation="true" :style="{ height: scrollHeight + 'px' }" @scroll="scroll">
				<view class="list">
					<block v-for="(item, index) in surroundingPois" :key="index">
						<view class="address-item" @click="setAddress(item)">
							<view class="tit font30 lh44">{{ item.name }}</view>
							<view class="con color-6B707C font26 lh38">{{ item.address }}</view>
							<view class="line"></view>
						</view>
					</block>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
import { jsAMap } from '@/static/js/jsAMap.js';
import SearchCustom from '@/components/search/search-custom.vue';
export default {
	components: { SearchCustom },
	data() {
		return {
			theme: getApp().globalData.appTheme,
			globalColor: getApp().globalData.globalColor,
			longitude: '',
			latitude: '',
			workAddress: '',
			workArea: '',
			ak: '20685b399d9c4b1f5e85a223a0e8d4b2',
			marker: null,
			keyword: '',
			AMap: null,
			map: null,
			scrollTop: 0,
			scrollHeight: 0,
			surroundingPois: [],
			locations: {}
		};
	},
	computed: {},
	onLoad(option) {
		uni.getSystemInfo({
			success: sys => {
				console.log(sys);
				this.scrollHeight = sys.screenHeight - getApp().globalData.statusBarHeight - 405;
			}
		});
		uni.showLoading({
			title: '定位中'
		});
		if (option && option.lng) {
			this.longitude = option.lng;
			this.latitude = option.lat;
			console.log('经纬度',this.longitude,this.latitude);
			this.getInit();
		} else {
			this.getLocation();
		}
		uni.setNavigationBarTitle({
			title: `搜索地址`
		});
	},
	mounted() {
		// #ifdef H5
		window.appCallback = this.appCallback;
		// #endif
	},
	methods: {
		getLocation() {
			const that = this;
			const data = { type: 'appLatLng' };
			this.$bridge.callHandler('recruitHandler', data, res => {
				console.log('recruitHandler', '返回', res);
				that.appCallback(res);
			});
			setTimeout(() => {
				if (!this.AMap) {
					uni.hideLoading();
					this.getInit();
				}
			}, 10000);
		},
		appCallback(e) {
			if (e.lng != 0 && e.lat != 0) {
				this.longitude = e.lng;
				this.latitude = e.lat;
			}
			this.getInit();
		},
		getInit() {
			const that = this;
			jsAMap(this.ak).then(AMap => {
				this.AMap = AMap;
				let config = {
					resizeEnable: true,
					zoom: 16
					// mapStyle: "amap://styles/dark"
				};
				if (that.latitude) {
					config.center = [that.longitude, that.latitude];
				}
				let map = new AMap.Map('container', config);
				uni.hideLoading();
				this.map = map;
				// map.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Geolocation', 'AMap.Geocoder']);
				if (!that.latitude) {
					map.plugin('AMap.Geolocation', () => {
						var geolocation = new AMap.Geolocation({
							enableHighAccuracy: true, //是否使用高精度定位，默认:true
							timeout: 10000, //超过10秒后停止定位，默认：无穷大
							maximumAge: 0, //定位结果缓存0毫秒，默认：0
							convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
							showButton: true, //显示定位按钮，默认：true
							buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
							buttonOffset: new AMap.Pixel(10, 20),
							showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
							showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
							panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
							zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
						});
						map.addControl(geolocation);
						geolocation.getCurrentPosition((s, r) => {
							console.log('s====================>', s);
							let address_now = {};
							if (s == 'complete') {
								console.log('成功定位信息', r);
								address_now.lng = r.position.lng;
								address_now.lat = r.position.lat;
							} else {
								console.log('失败定位信息', r);
								address_now = map.getCenter();
							}
							that.mapAddress(address_now.lng, address_now.lat);
							that.addMarker(address_now.lng, address_now.lat);
						});
					});
				} else {
					that.mapAddress(that.longitude, that.latitude);
					that.addMarker(that.longitude, that.latitude);
				}
				map.on('click', function(e) {
					that.longitude = e.lnglat.lng;
					that.latitude = e.lnglat.lat;
					that.scrollTop = 0;
					that.surroundingPois = [];
					that.mapAddress(e.lnglat.lng, e.lnglat.lat);
					that.addMarker(e.lnglat.lng, e.lnglat.lat);
				});
				map.on('zoomstart', function(e) {
					console.log('zoomstart', e);
				});
				map.on('zoomchange', function(e) {
					console.log('zoomchange', e);
				});
				map.on('zoomend', function(e) {
					console.log('zoomend', e);
				});
			});
		},
		getSearch() {
			const that = this;
			const AMap = this.AMap;
			const map = this.map;
			// 实例化Autocomplete
			map.plugin(['AMap.Autocomplete'], () => {
				var autoComplete = new AMap.Autocomplete({ city: '全国' });
				autoComplete.search(that.keyword, function(status, result) {
					console.log('Autocomplete', status, result);
					if (status === 'complete' && result.info == 'OK') {
						const address = result.tips[0];
						that.workArea = address.district;
						that.addMarker(address.location.lng, address.location.lat);
						that.surroundingPois = result.tips;
					}
				});
			});
		},
		mapAddress(lng, lat) {
			const that = this;
			const AMap = this.AMap;
			const map = this.map;
			let position = [lng, lat];
			map.plugin(['AMap.PlaceSearch', 'AMap.Geocoder'], () => {
				var geocoder = new AMap.Geocoder();
				var placeSearch = new AMap.PlaceSearch({ city: '全国' });
				geocoder.getAddress(position, (status, result) => {
					console.log('Geocoder', result);
					that.workArea = result.regeocode.addressComponent.district;
					if (status === 'complete' && result.info === 'OK') {
						placeSearch.search(result.regeocode.formattedAddress, function(status, result) {
							// 搜索成功时，result即是对应的匹配数据
							console.log('PlaceSearch', status, result);
							if (result.info == 'OK') {
								that.surroundingPois = result.poiList.pois;
							}
						});
					}
				});
			});
		},
		// 标注
		addMarker(lng, lat) {
			console.log('标注', lng, lat);
			const that = this;
			const AMap = this.AMap;
			const map = this.map;
			if (this.marker) {
				map.remove(this.marker);
			}
			map.setCenter([lng, lat]);
			const marker = new AMap.Marker({
				icon: new AMap.Icon({
					image: 'https://ebc-prod.cdn.benwunet.com/uni-static/location.png',
					size: new AMap.Size(28, 28), //图标所处区域大小
					imageSize: new AMap.Size(28, 28) //图标大小
				}),
				position: [lng, lat],
				offset: new AMap.Pixel(-13, -30)
			});
			this.marker = marker;
			map.add(marker);
		},
		setAddress(res) {
			const recruitmentTemp = getApp().globalData.recruitmentTemp;
			const that = this;
			const AMap = this.AMap;
			const map = this.map;
			let position = [res.location.lng, res.location.lat];
			map.plugin(['AMap.Geocoder'], () => {
				var geocoder = new AMap.Geocoder();
				geocoder.getAddress(position, (status, result) => {
					console.log('Geocoder', result);
					const {
						regeocode: {
							formattedAddress,
							addressComponent: { city, province, district }
						}
					} = result;
					recruitmentTemp.latitude = res.location.lat;
					recruitmentTemp.longitude = res.location.lng;
					recruitmentTemp.workAddress = formattedAddress;
					recruitmentTemp.workArea = `${city} ${province} ${district}`;
					recruitmentTemp.provinceName = province;
					recruitmentTemp.cityName = city ? city : -1;
					recruitmentTemp.districtName = district;
					uni.navigateBack({
						delta: 1
					});
				});
			});
		},
		scroll(e) {
			this.scrollTop = e.detail.scrollTop;
		}
	}
};
</script>

<style scoped lang="scss">
.page-wrap {
	min-height: calc(100vh);
}
.address-item {
	padding: 0 40rpx;
}
.list {
	padding: 40rpx 0 0;
}
.line {
	margin: 32rpx 0;
	height: 1rpx;
	background: var(--backgroundDivisionColor);
}
.tui-maps {
	width: 750rpx;
	height: 600rpx;
	// position: relative;
}
</style>
